<template>
  <div>
    <FilterInput
      v-if="!onlyView"
      v-model="paramsObj"
      :filter-list="filterList"
      line-feed
      class="FilterTool"
      show-search-btn
      @handelClick="queryClick"
      @queryEmpty="queryEmpty"/>
    <div v-loading="listLoading" class="table-container">
      <div v-if="!onlyView" class="opeator-top">
        <div class="tip">请勾选需要提交结算的订单</div>
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearAllCost" >
          <div>
            <span class="data-label">订单，结算金额 </span>
            <span v-if="totalPrice || totalPrice === 0" class="data-number">{{ (totalPrice/100) | moneyFilter(true, '元', true) }}</span>
            <span v-else class="data-number">--</span>
          </div>
          <template v-if="costBelong === 0 || costBelong === 5">
            <div style="margin-left:16px;">
              <span class="data-label">  含税金额 </span>
              <span v-if="taxAmountTotal || taxAmountTotal === 0" class="data-number">{{ (taxAmountTotal/100) | moneyFilter(true, '元', true) }}</span>
              <span v-else class="data-number">--</span>
            </div>
            <div style="margin-left:16px;">
              <span class="data-label">  总成本 </span>
              <span v-if="costAmountTotal || costAmountTotal === 0" class="data-number">{{ (costAmountTotal/100) | moneyFilter(true, '元', true) }}</span>
              <span v-else class="data-number">--</span>
            </div>
            <div style="margin-left:16px;">
              <span class="data-label">  毛利率 </span>
              <span v-if="profitTotal || profitTotal === 0" class="data-number">{{ profitTotal }}</span>
              <span v-else class="data-number">--</span>
            </div>
          </template>
        </SelectionNum>
      </div>

      <u-table
        v-if="settleOrder.items.length > 0"
        ref="orderTable"
        :data="settleOrder.items"
        :row-key="getRowKeys"
        :row-class-name="(data) => tableRowClassName(data, 'pointer')"
        :row-height="49"
        :border="false"
        :height="settleOrder.items.length > 10 ? 600 : ''"
        use-virtual
        element-loading-text="加载中..."
        empty-text="暂无数据"
        class="fb-table"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @select="onSelectTable"
        @select-all="onSelectTable">
        <!-- @sort-change="sortMethod" -->
        <!-- @selection-change="handleSelectionChange" -->
        <u-table-column
          align="center"
          type="selection"
          fixed="left"
          reserve-selction
          width="50"/>
        <u-table-column v-for="item in tableInfoSetting[costBelong.toString()]" v-bind="item.props" :key="item.key">
          <template slot-scope="scope">
            <orderTableRender :table-info="item" :table-data="scope.row" />
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else is-border mode="table" style="margin-bottom: 24px" />
      <div v-if="!onlyView" style="display: flex; justify-content: flex-end;">
        <el-pagination
          v-show="settleOrder.total > 0"
          :current-page="page"
          :page-size="perPage"
          :total="settleOrder.total"
          :page-sizes="[10, 20, 50, 100, 250, 500]"
          :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import { setting } from '@/components/SupplierComponent/module/orderTableInfo.js';
import orderTableRender from '@/components/SupplierComponent/module/orderTableRender';
import platformIcon from '@/components/Common/platformIcon';
// filters
import { moneyFilter } from '@/filters/number';
import { format } from '@/filters/date';
import { setOrderState } from '@/filters/status';
import math from '@/utils/math';
// mixins
import tableSelections from '@/mixins/tableSelections';
import { getOrderConfig } from '@/api/mengliOrder';
import { supplierSettleOrder } from '@/api/supplier';
import { orderFormList, platformList } from '@/api/select';
import { getOperateoptions } from '@/api/resource';
import { verificationOptions } from '@/views/project/model/selectData';
import { mapState } from 'vuex';

export default {
  filters: {
    moneyFilter, format, setOrderState,
    profitFilter(num) {
      const percent = Number(num) * 100;
      return percent.toFixed(2) + '%';
    }
  },
  components: { EmptyPlaceholder, platformIcon, orderTableRender },
  mixins: [tableSelections],
  props: {
    costId: {
      type: String | Number | Array,
      default: ''
    },
    supplierId: {
      type: String | Number,
      default: ''
    },
    costBelong: {
      type: Number,
      default: 0
    },
    stepOneData: {
      type: Object,
      default: null
    },
    stepTwoData: {
      type: Object,
      default: null
    },
    /**
     * 下面是协作请款用到的属性
     */
    isInviteOrder: {
      type: Boolean,
      default: false
    },
    onlyView: { // 仅显示不调用接口（新建已选tab）
      type: Boolean,
      default: false
    },
    isAddCost: { // 是否来子关联成本弹窗
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableInfoSetting: setting,
      page: 1,
      perPage: 10,
      selectData: [],
      listLoading: false,
      sortName: '',
      sortType: '',
      settleOrder: {
        items: [],
        total: 0
      },
      paramsObj: {
        orderId: ''
      },
      orderPlatformOption: [],
      orderFormOption: [],
      orderStatusOptions: [
        { value: 0, label: '草稿中' },
        { value: 1, label: '待发布' },
        { value: 3, label: '待审批' },
        { value: 4, label: '待封账' },
        { value: 5, label: '封账中' },
        { value: 6, label: '已封账' },
        { value: 7, label: '已完成' }
        // { value: 2, label: '待核算' },
      ],
      // { value: 2, label: '待核算' },
      tableRefName: 'orderTable', // 表格的ref名称
      idKey: 'orderCostItemId', // 唯一表示字段
      isUmyTable: true,
      // 获取row的key值
      getRowKeys(row) {
        return row.orderCostItemId;
      },
      operateModeList: [], // 运营模式
      themeList: [], // 合作类型
      areaList: [], // 合作品类

      costItemId: null, // 成本项ID
      costOrderId: null, // 成本ID  对应订单列表中的 orderCostItemId
      relatedOrderId: null, // 关联订单ID
      orderId: null // 订单编号
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isInvite() {
      return !!this.stepOneData.isInvite;
    },
    filterList() {
      //  0: '渠道订单',1: '项目订单',2: '商务订单',3: '营销授权',4: '电商销售',5: '项目渠道单'
      const costBelong = this.costBelong;
      let arr;
      if (costBelong === 0) {
        arr = [
        // 输入框
          { keyword: 'orderId', name: '订单编号', placeholder: '可通过粘贴快速填写订单编号，一行代表一个编号', type: 'input', inputType: 'textarea', maxlength: 2000, maxLength: 2000, lengthLimit: true },
          { keyword: 'market', name: '销售', type: 'input' },
          { keyword: 'resourceName', name: '账号', type: 'input' },
          { keyword: 'resourceId', name: '账号ID', type: 'input' },
          { keyword: 'cooperation', name: '合作运营方', type: 'input' },
          { keyword: 'organization', name: '所属机构', type: 'input' },
          { keyword: 'theme', name: '品牌名称', type: 'input' },
          { keyword: 'customerName', name: '客户名称', type: 'input' },
          { keyword: 'contractCode', name: '合同编号', type: 'input', lengthLimit: 50 },
          { keyword: 'writeOffStatus', name: '核销状态', type: 'select', options: verificationOptions },
          { keyword: 'cost', name: '结算金额', type: 'inputRange' },
          // 下拉
          { keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
          { keyword: 'orderStatus', name: '订单状态', type: 'select', options: this.orderStatusOptions },
          { keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label',
            childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList
          },
          // 日期
          { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
        ];
      } else if (costBelong === 1) {
        arr = [
          { keyword: 'projectNum', name: '项目编号', type: 'input' },
          { keyword: 'projectName', name: '项目名称', type: 'input' },
          { keyword: 'brandName', name: '品牌名称', type: 'input' },
          { keyword: 'customerName', name: '客户名称', type: 'input' },
          { keyword: 'contractCode', name: '合同编号', type: 'input', lengthLimit: 50 },
          { keyword: 'writeOffStatus', name: '核销状态', type: 'select', options: verificationOptions },
          { keyword: 'approvalTime', name: '立项日期', timeType: 'daterange', type: 'rangeDate' },
          { keyword: 'finishTime', name: '结案日期', timeType: 'daterange', type: 'rangeDate' }
        ];
      } else if (costBelong === 2) {
        arr = [
          { keyword: 'orderId', name: '订单编号', placeholder: '可通过粘贴快速填写订单编号，一行代表一个编号', type: 'input', inputType: 'textarea', maxlength: 2000, maxLength: 2000, lengthLimit: true },
          { keyword: 'customerName', name: '客户名称', type: 'input' },
          { keyword: 'market', name: '销售', type: 'input' },
          { keyword: 'areaId', name: '合作品类', type: 'select', options: this.areaList },
          { keyword: 'themeId', name: '合作类型', type: 'select', options: this.themeList },
          { keyword: 'ipFigure', name: 'IP形象', type: 'input' },
          { keyword: 'contractCode', name: '合同编号', type: 'input', lengthLimit: 50 },
          { keyword: 'writeOffStatus', name: '核销状态', type: 'select', options: verificationOptions },
          { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
        ];
      } else if (costBelong === 3) {
        arr = [
          { keyword: 'orderId', name: '订单编号', placeholder: '可通过粘贴快速填写订单编号，一行代表一个编号', type: 'input', inputType: 'textarea', maxlength: 2000, maxLength: 2000, lengthLimit: true },
          { keyword: 'customerName', name: '客户名称', type: 'input' },
          { keyword: 'market', name: '销售', type: 'input' },
          { keyword: 'ipFigure', name: 'IP形象', type: 'input' },
          { keyword: 'contractCode', name: '合同编号', type: 'input', lengthLimit: 50 },
          { keyword: 'writeOffStatus', name: '核销状态', type: 'select', options: verificationOptions },
          { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
        ];
      } else if (costBelong === 5) {
        arr = [
        // 输入框
          { keyword: 'orderId', name: '订单编号', placeholder: '可通过粘贴快速填写订单编号，一行代表一个编号', type: 'input', inputType: 'textarea', maxlength: 2000, maxLength: 2000, lengthLimit: true },
          { keyword: 'market', name: '销售', type: 'input' },
          { keyword: 'customerName', name: '客户名称', type: 'input' },
          { keyword: 'projectName', name: '项目名称', type: 'input' },
          { keyword: 'resourceName', name: '账号', type: 'input' },
          { keyword: 'resourceId', name: '账号ID', type: 'input' },
          { keyword: 'cooperation', name: '合作运营方', type: 'input' },
          { keyword: 'organization', name: '所属机构', type: 'input' },
          { keyword: 'theme', name: '品牌名称', type: 'input' },
          { keyword: 'contractCode', name: '合同编号', type: 'input', lengthLimit: 50 },
          { keyword: 'cost', name: '结算金额', type: 'inputRange' },
          // 下拉
          { keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
          { keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label',
            childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList
          },
          { keyword: 'writeOffStatus', name: '核销状态', type: 'select', options: verificationOptions },
          // 日期
          { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' }
        ];
      }
      return arr;
    },
    totalPrice() {
      let totalPrice = 0;
      this.selectData.forEach((i) => {
        totalPrice = math.add(totalPrice, i.costPrice ? i.costPrice : i.taxCost || 0);
      });
      return totalPrice;
    },
    taxAmountTotal() {
      let totalPrice = 0;
      const uniqueOrder = [];
      this.selectData.forEach((i) => {
        if (!uniqueOrder.includes(i.orderId)) {
          uniqueOrder.push(i.orderId);
          totalPrice = math.add(totalPrice, i.taxAmount || 0);
        }
      });
      return totalPrice;
    },
    costAmountTotal() {
      let totalPrice = 0;
      const uniqueOrder = [];
      this.selectData.forEach((i) => {
        if (!uniqueOrder.includes(i.orderId)) {
          uniqueOrder.push(i.orderId);
          totalPrice = math.add(totalPrice, i.orderCost || 0);
        }
      });
      return totalPrice;
    },
    profitTotal() {
      let totalPrice = 0;
      if (this.selectData && this.selectData.length) {
        if (this.taxAmountTotal) { // taxAmountTotal不能为0
          totalPrice = math.divide(math.subtract(this.taxAmountTotal, this.costAmountTotal), this.taxAmountTotal);
        }
        return (math.multiply(totalPrice, 100)).toFixed(2) + '%';
      }
      return '--';
    }
  },
  watch: {
    costId() {
      this.getOrderList(true);
    }
  },
  created() {
    // 从成本列表结算而来才会有下面4个属性，用于自动选择成本或订单
    this.costItemId = Number(this.$route.query.costItemId) || null; // 成本项ID
    this.costOrderId = Number(this.$route.query.costId) || null; // 成本ID
    this.relatedOrderId = Number(this.$route.query.relatedOrderId) || null; // 关联订单ID
    this.orderId = this.$route.query.orderId || null; // 订单编号

    if (this.orderId) {
      if (this.costBelong === 1) {
        this.paramsObj.projectNum = this.orderId;
      } else {
        this.paramsObj.orderId = this.orderId;
      }
    }
    if (this.$route.query.legalId) {
      this.$set(this.paramsObj, 'contractCode', this.stepOneData && this.stepOneData.contractCode);
    }
    if (!this.onlyView) {
      this.getOrderList();
      this.platformList();
      this.getOperateMode();
      this.getOrderConfig();
      // this.getOrderForm();
    }
  },
  methods: {
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.getOrderList();
    },
    // 获取萌力星球订单配置项
    async getOrderConfig() {
      try {
        const res = await getOrderConfig();
        this.areaList = res.data.areaList;
        this.themeList = res.data.themeList;
        this.areaList.map(el => {
          // eslint-disable-next-line no-sequences
          el.value = el.id,
          el.label = el.name;
        });
        this.themeList.map(el => {
          // eslint-disable-next-line no-sequences
          el.value = el.id,
          el.label = el.name;
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 下单平台
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取下单形式
    async getOrderForm() {
      try {
        const result = await orderFormList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderFormOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取运营模式
    async getOperateMode() {
      try {
        const res = await getOperateoptions();
        this.operateModeList = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    getOrderList(reset = false) {
      if (this.onlyView) return;
      const costIds = this.costItemId || (Array.isArray(this.costId) ? this.costId.join() : this.costId);
      if (!costIds) {
        this.settleOrder = {
          items: [],
          total: 0
        };
        return;
      }
      if (reset) this.page = 1;
      const params = {
        costIds: costIds,
        supplierId: this.supplierId,
        page: this.page,
        perPage: this.perPage,
        costBelong: this.costBelong || 0
      };
      if (this.$route.query.settleId && !this.isInviteOrder && !this.isAddCost) {
        params.settleId = this.$route.query.settleId;
      }
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      const filterParams = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      if (filterParams.approvalTime && filterParams.approvalTime.length === 2) {
        filterParams.projectApprovalStart = Math.round(filterParams.approvalTime[0] / 1000);
        filterParams.projectApprovalEnd = Math.round(filterParams.approvalTime[1] / 1000);
      }
      if (filterParams.finishTime && filterParams.finishTime.length === 2) {
        filterParams.finishStart = Math.round(filterParams.finishTime[0] / 1000);
        filterParams.finishEnd = Math.round(filterParams.finishTime[1] / 1000);
      }
      if (filterParams.orderTime && filterParams.orderTime.length === 2) {
        filterParams.orderTimeStart = Math.round(filterParams.orderTime[0] / 1000);
        filterParams.orderTimeEnd = Math.round(filterParams.orderTime[1] / 1000);
      }
      if (filterParams.cost && filterParams.cost.length === 2) {
        filterParams.costStart = filterParams.cost[0] || filterParams.cost[0] === 0 ? (Number(filterParams.cost[0]).toFixed(2) * 100).toFixed(0) : null;
        filterParams.costEnd = filterParams.cost[1] || filterParams.cost[1] === 0 ? (Number(filterParams.cost[1]).toFixed(2) * 100).toFixed(0) : null;
      }

      delete filterParams.approvalTime;
      delete filterParams.finishTime;
      delete filterParams.cost;
      delete filterParams.orderTime;
      Object.assign(params, filterParams);
      const AllSelectedCost = this.stepTwoData.cost || [];
      this.listLoading = true;
      supplierSettleOrder(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.settleOrder = res.data;
          this.selectFun(res.data.items, AllSelectedCost);
          if (this.setSelectRow) this.setSelectRow(res.data.items);
          if (res.data.otherData.differenceSn) {
            this.$message({
              dangerouslyUseHTMLString: true,
              type: 'warning',
              message: `<div>编号${res.data.otherData.differenceSn.join('<br>')}的订单/成本不存在或无权限或状态为结算中/结算完成</div>`
            });
          }
        }
      }).catch(e => {
        this.listLoading = false;
      });
    },
    queryClick() {
      this.getOrderList(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      if (this.clearMixinSelection) this.clearMixinSelection();
      this.getOrderList(true);
    },
    onSelectTable(selection, row) {
      this.onlyView ? this.$emit('orderSelectedReset', selection) : this.selectTable(selection, row);
    },
    clearAllCost() {
      this.clearMixinSelection();
      this.$nextTick(() => {
        this.$emit('orderSelectedReset', []);
      });
    },
    toCheck(scope) {
      let routeUrl = null;
      routeUrl = this.$router.resolve({
        name: 'orderDetail',
        params: { orderId: scope.row.id }
      });
      if (routeUrl) window.open(routeUrl.href, '_blank');
    },
    // 选中订单
    tableSelectionChange(e) {
      this.selectData = e;
      this.$emit('selectData', this.multipleSelectionAll);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getOrderList(true);
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getOrderList();
    },
    selectFun(list, AllSelectedCost = []) {
      const setData = new Set(); // 去重用
      // 从下一步返回回来后需要 取出 stepTwoData的数据进行回填
      if (AllSelectedCost.length) {
        if (Array.isArray(this.costId)) {
          const allOrderList = [];
          AllSelectedCost.forEach(cost => {
            allOrderList.push(...cost.orderIds);
          });
          this.multipleSelectionAll = allOrderList;
          this.$emit('orderSelectedReset', allOrderList);
          this.$nextTick(() => {
            this.stepTwoData.cost = [];
          });
        } else {
          const currentCost = AllSelectedCost.find(i => i.costId === this.costId);
          if (currentCost && currentCost.orderIds && currentCost.orderIds.length) {
            const cacheOrderList = currentCost.orderIds.filter(i => {
              return !this.multipleSelectionAll.map(row => row.orderCostItemId).includes(i.orderCostItemId);
            });
            this.multipleSelectionAll = this.multipleSelectionAll.concat(cacheOrderList);
          }
        }
      }
      this.tableSelectionChange(this.multipleSelectionAll);

      if (this.relatedOrderId) setData.add(this.costOrderId);

      let ids = [...setData];
      ids = ids.filter(i => !this.multipleSelectionAll.map(row => row.orderCostItemId).includes(i));
      if (ids.length > 0) {
        this.$nextTick(() => {
          for (var i = 0; i < list.length; i++) {
            if (ids.includes(list[i].orderCostItemId)) {
              this.multipleSelectionAll.push(list[i]);
              this.tableSelectionChange(this.multipleSelectionAll);
            }
          }
        });
      }
    },
    parseObj(str) {
      try {
        return JSON.parse(str);
      } catch (error) {
        return [];
      }
    },
    // 勾选状态重置
    resetSelectStatus() {
      this.$nextTick(() => {
        const selectedIds = this.multipleSelectionAll.map(i => i.id);
        this.settleOrder.items.forEach(row => {
          this.$refs['orderTable'].toggleRowSelection(row, selectedIds.includes(row.id));
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.FilterTool {
  margin-top: 12px;
  &::v-deep {
    .el-date-editor {
      &.el-input__inner {
        width: 240px !important;
      }
    }
  }
}
.data-label {
  font-size: 14px;
  color: #666;
}
.data-number {
  font-size: 14px;
  color: #406eff;
  font-weight:600;
}
.table-container {
  .opeator-top {
    display: flex;
    margin: 6px 0;
    height: 32px;
    align-items: center;
    @include scrollBar($x: auto, $y: hidden, $width: 6px);
  }
  .tip {
    color: #999;
    font-size: 13px;
    margin-right:20px;
    white-space: nowrap;
  }
  .order-id {
    color: #406eff;
    cursor: pointer;
  }
}
</style>
